const path = require('path')
const fs = require('fs')
const { promisify } = require('util')

const mkdir = promisify(fs.mkdir)
const writeFile = promisify(fs.writeFile)
const accessFile = promisify(fs.access)
const unlinkFile = promisify(fs.unlink)

const logger = require('../utils/logger')

let isDev = process.env.NODE_ENV === 'development'
const publicPath = isDev ? '../assets/images' : process.env.UPLOAD_PATH

/**
 *
 * @returns 头像列表
 */
const filesList = () => {
  let directoryPath = path.resolve(__dirname, publicPath)

  const avatarsPath = path.join(directoryPath, 'avatars')

  const files = fs.readdirSync(avatarsPath)
  return files
}

/**
 *
 * @param {*} data 文件
 * @param {*} url 保存地址 （路径）
 * @returns
 */
const fileUpload = async (data, prefix, url) => {
  const fileName = Date.now() + path.extname(data.filename)

  let filePath
  if (isDev) {
    filePath = path.join(__dirname, `${publicPath}/${prefix}`, fileName)
  } else {
    filePath = path.join(`${publicPath}/${prefix}`, fileName)
  }
  await mkdir(path.dirname(filePath), { recursive: true })
  const result = await writeFile(filePath, await data.toBuffer())

  let fileUrl = isDev
    ? `http://127.0.0.1:3000/images/${prefix}/${fileName}`
    : `https://www.tjhuabo.com.cn/images/${prefix}/${fileName}`

  if (!result) {
    return {
      message: '上传成功！',
      data: {
        code: 200,
        fileUrl,
        fileName: data.filename,
        filePath: url,
        fileTimeName: fileName,
      },
    }
  } else {
    logger.error(result)
    return {
      message: '上传失败！',
      data: filePath,
      code: 400,
    }
  }
}

/**
 *
 * @param {*} url  删除路径
 * @param {*} _file  文件名
 * @returns
 */
const deleteFile = async (prefix, url, _file) => {
  const filePath = path.resolve(
    __dirname,
    `${publicPath}/${prefix}/${url}/${_file}`
  )
  try {
    await accessFile(filePath, fs.constants.F_OK)
    try {
      await unlinkFile(filePath)
      return {
        message: '文件删除成功！',
        data: null,
        error: null,
        code: 200,
      }
    } catch (unlinkError) {
      logger.error(unlinkError, '该文件删除失败！')
      return {
        message: '该文件删除失败！',
        data: null,
        error: unlinkError,
        code: 400,
      }
    }
  } catch (error) {
    logger.error(error, '未找到需要删除的文件！')
    return {
      message: '删除失败，未查询到文件！',
      data: null,
      error: error.message,
      code: 404,
    }
  }
}
module.exports = {
  fileUpload,
  deleteFile,
  filesList,
}
